<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Search, Refresh } from '@element-plus/icons-vue'
import { getClazzPage, addClazz, updateClazz, deleteClazz, batchDeleteClazz, exportClazz } from '@/api/clazz.js'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

import { Download, Upload } from '@element-plus/icons-vue'

// 上传携带 token（有就留，没有可删）
const uploadHeaders = { Authorization: localStorage.getItem('token') }

/* 导出：axios 下载 */
const handleExport = async () => {
    try {
        const blob = await exportClazz()
        const fileName = '班级信息.xlsx'
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(link.href)
    } catch (e) {
        ElMessage.error('导出失败')
    }
}

/* ====== 导入：axios 上传 ====== */
const importSuccess = (res) => {
    ElMessage.success(res.message || '导入成功')
    getData()
}
const importError = (err) => {
    ElMessage.error(err.message || '导入失败')
}
/* 表格数据 */
const tableData = ref([])
const loading = ref(false)

/* 分页 */
const pagination = ref({
    currentPage: 1,
    pageSize: 6,
    total: 0
})

/* 搜索条件 */
const queryForm = ref({
    grade: null,
    className: ''
})

/* 弹窗 */
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const formData = ref({
    id: null,
    className: '',
    classNum: '',
    grade: null,
    majorId: null,
    personCount: '',
    headTeacher: '',
    phone: '',
    status: 1
})

const rules = {
    className: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
    classNum: [{ required: true, message: '请输入班级编号', trigger: 'blur' }],
    grade: [{ required: true, message: '请选择入学年份', trigger: 'change' }],
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
    personCount: [{ required: true, message: '请输入班级人数', trigger: 'blur' }, { type: 'number', min: 0, max: 200, message: '人数范围 0-200', trigger: 'blur' }]
}

/* 拉数据 */
const getData = async () => {
    loading.value = true
    const params = {
        currentPage: pagination.value.currentPage,
        pageSize: pagination.value.pageSize,
        ...queryForm.value
    }
    const res = await getClazzPage(params)
    console.log(res.data.list)
    tableData.value = res.data.list
    pagination.value.total = res.data.total
    loading.value = false
}

/* 分页大小变化 */
const handleSizeChange = (val) => {
    pagination.value.pageSize = val
    getData()
}
const handleCurrentChange = (val) => {
    pagination.value.currentPage = val
    getData()
}

/* 新增/编辑 */
const handleAdd = () => {
    dialogTitle.value = '新增班级'
    resetForm()
    dialogVisible.value = true
}
const handleEdit = (row) => {
    dialogTitle.value = '编辑班级'
    formData.value = { ...row }
    dialogVisible.value = true
}

/* 提交 */
const submitForm = async () => {
    await formRef.value.validate()
    const api = formData.value.id ? updateClazz : addClazz
    const res = await api(formData.value)
    ElMessage.success(res.message)
    dialogVisible.value = false
    getData()
}

/* 删除 */
const handleDelete = (id) => {
    ElMessageBox.confirm('确定删除该班级？', '提示', { type: 'warning' })
        .then(async () => {
            const res = await deleteClazz(id)
            ElMessage.success(res.message)
            getData()
        })
        .catch(() => ElMessage.info('已取消'))
}

/* 批量删除 */
const selectedIds = ref([])
const handleSelectionChange = (rows) => {
    selectedIds.value = rows.map(r => r.id)
}
const handleBatchDelete = async () => {
    if (!selectedIds.value.length) return ElMessage.warning('请至少选择一条')
    ElMessageBox.confirm(`将删除 ${selectedIds.value.length} 条数据，继续？`, '提示', { type: 'warning' })
        .then(async () => {
            const res = await batchDeleteClazz(selectedIds.value)
            ElMessage.success(res.message)
            getData()
        })
        .catch(() => ElMessage.info('已取消'))
}

/* 重置 */
const resetForm = () => {
    formData.value = {
        id: null,
        className: '',
        classNum: '',
        grade: null,
        majorId: null,
        personCount: '',
        headTeacher: '',
        phone: '',
        status: 1
    }
}

onMounted(() => getData())
</script>

<template>
    <div class="app-container">
        <!-- 搜索区 -->
        <el-form :inline="true" :model="queryForm" class="demo-form-inline">
            <el-form-item label="入学年份">
                <el-date-picker v-model="queryForm.grade" type="year" placeholder="选择年" value-format="YYYY" />
            </el-form-item>
            <el-form-item label="班级名称">
                <el-input v-model="queryForm.className" placeholder="模糊查询" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="getData">搜索</el-button>
                <el-button :icon="Refresh" @click="queryForm = {}; getData()">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 按钮区 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
            </el-col>

            <!-- 导入 -->
            <el-col :span="1.5">
                <el-upload :action="'http://localhost:8080/api/clazz/import'" :headers="uploadHeaders" :show-file-list="false"
                    :on-success="importSuccess" :on-error="importError" accept=".xlsx,.xls"
                    style="display: inline-block; margin-left: 10px">
                    <el-button type="success" :icon="Download">导入</el-button>
                </el-upload>
            </el-col>

            <!-- 导出 -->
            <el-col :span="1.5">
                <el-button type="info" :icon="Upload" @click="handleExport">导出</el-button>
            </el-col>
        </el-row>

        <!-- 表格 -->
        <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange" row-key="id">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="70" />
            <el-table-column prop="className" label="班级名称" width="120" />
            <el-table-column prop="classNum" label="班级编号" width="100" />
            <el-table-column prop="personCount" label="班级人数" width="100" align="center" />

            <el-table-column prop="grade" label="入学年份" width="100" />
            <el-table-column prop="headTeacher" label="班主任" width="100" />
            <el-table-column prop="phone" label="联系电话" width="120" />
            <el-table-column prop="status" label="状态" width="80">
                <template #default="{ row }">
                    <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                        {{ row.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="180" fixed="right" align="center">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
                    <el-button link type="danger" @click="handleDelete(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-config-provider :locale="zhCn">
            <el-pagination background layout="total, sizes, prev, pager, next, jumper"
                v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-config-provider>

        <!-- 新增/编辑弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500">
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="100">
                <el-form-item label="班级名称" prop="className">
                    <el-input v-model="formData.className" placeholder="如：软件工程1班" />
                </el-form-item>
                <el-form-item label="班级编号" prop="classNum">
                    <el-input v-model="formData.classNum" placeholder="全局唯一编号" />
                </el-form-item>
                <el-form-item label="班级人数" prop="personCount">
                    <el-input-number v-model="formData.personCount" :min="0" :step="1" controls-position="right"
                        placeholder="班级人数" style="width: 100%" />
                </el-form-item>
                <el-form-item label="入学年份" prop="grade">
                    <el-date-picker v-model="formData.grade" type="year" placeholder="选择年" value-format="YYYY" />
                </el-form-item>
                <el-form-item label="专业">
                    <el-input v-model="formData.majorId" placeholder="专业id（可先空）" />
                </el-form-item>
                <el-form-item label="班主任">
                    <el-input v-model="formData.headTeacher" placeholder="班主任姓名" />
                </el-form-item>
                <el-form-item label="联系电话">
                    <el-input v-model="formData.phone" pattern: placeholder="手机号" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" inline-prompt
                        active-text="启用" inactive-text="禁用" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.app-container {
    padding: 20px;
}

.mb8 {
    margin-bottom: 8px;
}
</style>